#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/3 10:43
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : headers.py
import requests
import configparser
from ProjectPath import projectPath
import json
from common.readConfig import ReadConfig
from common.cryptoTool import RsaCrypto

# 获取url前缀
serviceUrl = ReadConfig().get_http("serviceUrl")
confDir = projectPath + '/config/'

# 获取登录token，并返回一个字典，其他接口调用时，需要在headers中添加此字典
class GetToken:
    def __init__(self):
        cf = configparser.ConfigParser()
        cf.read(filenames=confDir + 'cookie.ini', encoding='utf-8')
        # 获取url地址
        self.requestUrl = cf.get("COOKIE_CONFIG", "requestUrl")
        self.requestParams = cf.get("COOKIE_CONFIG", "params")
        self.headers = cf.get("COOKIE_CONFIG", "headers")

    def login_token(self,session):
        requestParams = self.get_param()
        url = serviceUrl + self.requestUrl
        result = session.post(url=url,json=requestParams,headers=json.loads(self.headers))
        token = json.loads(result.text)["token"]
        # 后来发现session地址一样，不用再return返回，不过这种方法也能用
        return session,{"Authorization":token}

    def get_param(self):
        '''通过加密方法将密码加密'''
        params = eval(self.requestParams)
        password = params['password']
        passwdEncry = RsaCrypto().loginPWDEncrypt(password)
        params['password'] = passwdEncry
        return params


if __name__ == '__main__':
    session = requests.session()
    # print(requestParams)
    print(GetToken().login_token(session))
    # print(GetToken().get_param())
